package bookManager;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by xiebang
 * Description
 * User:小谢
 * Date:2021-11-29
 * Time:17:42
 */

//通过数据库的连接操作,封装起来
public class DBUtil {
    private static String url = "jdbc:mysql://127.0.0.1:3306/java101BookManager?characterEncoding=utf8&useSSL=false";
    private static String username = "root";
    private static String password = "xcb@19980521";

    //接下来就需要创建DataSource实例
    //实际上一个程序中只需要一个DataSource对象就行,像DataSource这样的实例,不应该被创建多个.
    private static DataSource dataSource = new MysqlDataSource();

    //静态代码块,执行实际是在类加载阶段
    static {
        ((MysqlDataSource)dataSource).setURL(url);
        ((MysqlDataSource)dataSource).setUser(username);
        ((MysqlDataSource)dataSource).setPassword(password);
    }

    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    //释放资源
    public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet){

        /*
        这样是有风险的,一旦上面的代码出现异常,下面的代码就会被跳过
         */
//        try {
//            if (resultSet != null){
//                resultSet.close();
//            }
//            if (statement != null){
//                statement.close();
//            }
//            if (connection != null){
//                connection.close();
//            }
//        }catch (SQLException e){
//
//        }
        if (resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if (statement != null){
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if (connection != null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }


}
